package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuelao.yuelao_backend.common.ConfigConstants;
import com.yuelao.yuelao_backend.dto.DailyActionStatsDTO;
import com.yuelao.yuelao_backend.enums.SystemMessageType;
import com.yuelao.yuelao_backend.entity.DailyUserStats;
import com.yuelao.yuelao_backend.mapper.DailyUserStatsMapper;
import com.yuelao.yuelao_backend.service.DailyActionRecordService;
import com.yuelao.yuelao_backend.service.SystemConfigService;
import com.yuelao.yuelao_backend.service.SystemMessageService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 每日操作记录Service实现类
 */
@Service
public class DailyActionRecordServiceImpl extends ServiceImpl<DailyUserStatsMapper, DailyUserStats> implements DailyActionRecordService {


    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private SystemMessageService systemMessageService;

    // 获取每日限制配置值（使用公共缓存方法和公共常量）
    private int getNormalLikeLimit() {
        return systemConfigService.getCachedConfigInt(ConfigConstants.GROUP_ACTION_LIMITS, 
                ConfigConstants.KEY_NORMAL_LIKE_LIMIT, ConfigConstants.DEFAULT_NORMAL_LIKE_LIMIT);
    }

    private int getVipLikeLimit() {
        return systemConfigService.getCachedConfigInt(ConfigConstants.GROUP_ACTION_LIMITS, 
                ConfigConstants.KEY_VIP_LIKE_LIMIT, ConfigConstants.DEFAULT_VIP_LIKE_LIMIT);
    }

    private int getNormalSuperLikeLimit() {
        return systemConfigService.getCachedConfigInt(ConfigConstants.GROUP_ACTION_LIMITS, 
                ConfigConstants.KEY_NORMAL_SUPER_LIKE_LIMIT, ConfigConstants.DEFAULT_NORMAL_SUPER_LIKE_LIMIT);
    }

    private int getVipSuperLikeLimit() {
        return systemConfigService.getCachedConfigInt(ConfigConstants.GROUP_ACTION_LIMITS, 
                ConfigConstants.KEY_VIP_SUPER_LIKE_LIMIT, ConfigConstants.DEFAULT_VIP_SUPER_LIKE_LIMIT);
    }

    private int getNormalFollowLimit() {
        return systemConfigService.getCachedConfigInt(ConfigConstants.GROUP_ACTION_LIMITS, 
                ConfigConstants.KEY_NORMAL_FOLLOW_LIMIT, ConfigConstants.DEFAULT_NORMAL_FOLLOW_LIMIT);
    }

    private int getVipFollowLimit() {
        return systemConfigService.getCachedConfigInt(ConfigConstants.GROUP_ACTION_LIMITS, 
                ConfigConstants.KEY_VIP_FOLLOW_LIMIT, ConfigConstants.DEFAULT_VIP_FOLLOW_LIMIT);
    }


    @Override
    public DailyUserStats getTodayRecord(Long userId) {
        LocalDate today = LocalDate.now();
        LambdaQueryWrapper<DailyUserStats> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DailyUserStats::getUserId, userId)
                .eq(DailyUserStats::getDate, today);
        DailyUserStats record = getOne(wrapper);

        if (record == null) {
            // 创建今日记录
            record = new DailyUserStats();
            record.setUserId(userId);
            record.setDate(today);
            record.setLikeCount(0);
            record.setSuperLikeCount(0);
            record.setFollowCount(0);
            record.setPostCount(0);
            record.setCommentCount(0);
            record.setNewMatches(0);
            record.setNewFollowers(0);
            record.setAdWatchCount(0);
            record.setLoginCount(0);
            record.setActiveMinutes(0);
            record.setCreatedAt(LocalDateTime.now());
            record.setUpdatedAt(LocalDateTime.now());
            save(record);
        }
        return record;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean incrementLikeCount(Long userId, boolean isSuper) {
        DailyUserStats record = getTodayRecord(userId);
        if (isSuper) {
            record.setSuperLikeCount(record.getSuperLikeCount() + 1);
        } else {
            record.setLikeCount(record.getLikeCount() + 1);
        }
        record.setUpdatedAt(LocalDateTime.now());
        return updateById(record);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean incrementFollowCount(Long userId) {
        DailyUserStats record = getTodayRecord(userId);
        record.setFollowCount(record.getFollowCount() + 1);
        record.setUpdatedAt(LocalDateTime.now());
        return updateById(record);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean incrementMatchCount(Long userId) {
        DailyUserStats record = getTodayRecord(userId);
        record.setNewMatches(record.getNewMatches() + 1);
        record.setUpdatedAt(LocalDateTime.now());
        return updateById(record);
    }


    @Override
    public boolean canLikeToday(Long userId, boolean isVip) {
        DailyUserStats record = getTodayRecord(userId);
        int limit = isVip ? getVipLikeLimit() : getNormalLikeLimit();
        return record.getLikeCount() < limit;
    }


    @Override
    public boolean canSuperLikeToday(Long userId, boolean isVip) {
        if (!isVip) {
            return false; // 普通用户没有超级喜欢权限
        }
        DailyUserStats record = getTodayRecord(userId);
        return record.getSuperLikeCount() < getVipSuperLikeLimit();
    }


    @Override
    public boolean canFollowToday(Long userId, boolean isVip) {
        DailyUserStats record = getTodayRecord(userId);
        int limit = isVip ? getVipFollowLimit() : getNormalFollowLimit();
        return record.getFollowCount() < limit;
    }


    @Override
    public DailyActionStatsDTO getTodayStats(Long userId, boolean isVip) {
        DailyUserStats record = getTodayRecord(userId);

        DailyActionStatsDTO stats = new DailyActionStatsDTO();
        stats.setLikeCount(record.getLikeCount());
        stats.setLikeLimit(isVip ? getVipLikeLimit() : getNormalLikeLimit());
        stats.setSuperLikeCount(record.getSuperLikeCount());
        stats.setSuperLikeLimit(isVip ? getVipSuperLikeLimit() : getNormalSuperLikeLimit());
        stats.setFollowCount(record.getFollowCount());
        stats.setFollowLimit(isVip ? getVipFollowLimit() : getNormalFollowLimit());
        stats.setNewMatches(record.getNewMatches());
        
        // 通过系统消息未读数量统计被喜欢、被超级喜欢、被关注的次数
        stats.setByLikeCount((int) systemMessageService.getUnreadCountByType(userId, SystemMessageType.LIKE.getCode()));
        stats.setBySuperLikeCount((int) systemMessageService.getUnreadCountByType(userId, SystemMessageType.SUPER_LIKE.getCode()));
        stats.setByFollowCount((int) systemMessageService.getUnreadCountByType(userId, SystemMessageType.FOLLOW.getCode()));
        
        return stats;
    }
}

